import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class CollaborativeCatchGame extends JFrame {
    public static void main(String[] args) {
        JFrame frame = new JFrame("协作接球游戏");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 500);

        GamePanel panel = new GamePanel();
        frame.add(panel);
        frame.setVisible(true);

        new Thread(panel).start(); // 启动球生成线程
    }
}

class GamePanel extends JPanel implements Runnable, KeyListener {
    private volatile int leftBasketX = 100;
    private volatile int rightBasketX = 400;
    private final int BASKET_WIDTH = 60;
    private final int BASKET_Y = 400;
    private AtomicInteger score = new AtomicInteger(0);
    private List<Ball> balls = new ArrayList<>();

    public GamePanel() {
        addKeyListener(this);
        setFocusable(true);
        setBackground(Color.WHITE);
    }

    @Override
    public void run() {
        while (true) {
            Ball ball = new Ball(this);
            synchronized (balls) {
                balls.add(ball);
            }
            new Thread(ball).start();

            try {
                Thread.sleep(2000); // 每2秒生成新球
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // 绘制篮子
        g.setColor(Color.BLUE);
        g.fillRect(leftBasketX, BASKET_Y, BASKET_WIDTH, 20);
        g.fillRect(rightBasketX, BASKET_Y, BASKET_WIDTH, 20);

        // 绘制所有球
        synchronized (balls) {
            for (Ball ball : balls) {
                ball.draw(g);
            }
        }

        // 显示得分
        g.setColor(Color.BLACK);
        g.drawString("得分: " + score.get(), 10, 20);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        int step = 15;

        // 左玩家控制左篮子（方向键）
        if (key == KeyEvent.VK_LEFT) {
            leftBasketX = Math.max(0, leftBasketX - step);
        } else if (key == KeyEvent.VK_RIGHT) {
            leftBasketX = Math.min(getWidth() - BASKET_WIDTH, leftBasketX + step);
        }

        // 右玩家控制右篮子（A/D键）
        if (key == KeyEvent.VK_A) {
            rightBasketX = Math.max(0, rightBasketX - step);
        } else if (key == KeyEvent.VK_D) {
            rightBasketX = Math.min(getWidth() - BASKET_WIDTH, rightBasketX + step);
        }

        repaint();
    }

    public void removeBall(Ball ball) {
        synchronized (balls) {
            balls.remove(ball);
        }
        repaint();
    }

    // KeyListener接口其他方法
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}

    // Getters
    public int getLeftBasketX() { return leftBasketX; }
    public int getRightBasketX() { return rightBasketX; }
    public int getBasketY() { return BASKET_Y; }
    public int getBasketWidth() { return BASKET_WIDTH; }
    public AtomicInteger getScore() { return score; }
}

class Ball implements Runnable {
    private static final int BALL_SIZE = 20;
    private int x;
    private int y;
    private int speed;
    private GamePanel panel;

    public Ball(GamePanel panel) {
        this.panel = panel;
        x = (int) (Math.random() * (panel.getWidth() - BALL_SIZE));
        y = 0;
        speed = (int) (Math.random() * 3 + 2); // 下落速度2-4像素/帧
    }

    public void draw(Graphics g) {
        g.setColor(Color.RED);
        g.fillOval(x, y, BALL_SIZE, BALL_SIZE);
    }

    @Override
    public void run() {
        while (y < panel.getHeight()) {
            y += speed;

            // 碰撞检测
            if (y + BALL_SIZE >= panel.getBasketY()) {
                int ballCenter = x + BALL_SIZE/2;
                int leftBasket = panel.getLeftBasketX();
                int rightBasket = panel.getRightBasketX();
                int basketWidth = panel.getBasketWidth();

                if ((ballCenter >= leftBasket && ballCenter <= leftBasket + basketWidth) ||
                        (ballCenter >= rightBasket && ballCenter <= rightBasket + basketWidth)) {
                    panel.getScore().addAndGet(10); // 接球成功+10分
                    break;
                }
            }

            // 更新UI
            SwingUtilities.invokeLater(() -> panel.repaint());

            try {
                Thread.sleep(30); // 控制下落速度
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (y >= panel.getHeight()) {
            panel.getScore().addAndGet(-5); // 漏接-5分
        }
        panel.removeBall(this);
    }
}